/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <QVariant>
#include <QFile>
#include <QFileInfo>
#include <QRegExp>
#include "karehaagent.h"
#include "log.h"
#include "components/chan.h"
#include "components/board.h"
#include "network/request.h"

namespace Wishmaster
{
	KarehaAgent::KarehaAgent(const QString& host) : DefaultAgent(host),
		m_host(host)
	{
	}

	KarehaAgent::~KarehaAgent()
	{
	}

	void KarehaAgent::getCaptcha(const ThreadId& threadId)
	{
		QString captchascript;
		if(threadId.threadNumericId() > 0)
			captchascript = property("postcaptchascript").toString();
		else
			captchascript = property("threadcaptchascript").toString();
		captchascript.replace("%BOARD%", threadId.boardId());
		if(captchascript.isEmpty())
			return;

		RequestPtr request = connector()->makeRequest(m_host, captchascript);
		request->setProperty("thread_id", QVariant::fromValue(threadId));
		connector()->connectRequest(this, SLOT(resultCaptcha(RequestPtr, const QByteArray&)), 0, request);
		connector()->queue(request);
	}

	void KarehaAgent::makePost(const PostDescriptor& post, const QString& captcha, const BoardConstraints& /*constraints*/)
	{
		m_threadID = post.parent_thread.threadNumericId();
		m_board = post.board;
		QString karehascript = property("karehascript").toString();
		karehascript.replace("%BOARD%", m_board);

		HttpRequestPtr request = connector()->makeHttpRequest(m_host, karehascript, "POST");
//		if(!m_captchaCookie.isEmpty())
//			request->setCookieString("captchakey=" + m_captchaCookie);
		request->addPostField("task", "post");
		request->addPostField("name", "");
		request->addPostField("link", "");
		request->addPostField("thread", post.parent_thread.threadStringId());
		request->addPostField(property("field1name").toString(), post.name);
		request->addPostField(property("field2name").toString(), post.email);
		request->addPostField("markup", "waka");
		request->addPostField(property("field4name").toString(), post.text);
		addAttachments(request, post.attachments.count() > 0 ? post.attachments.at(0) : AttachmentDescriptor(), "file");
		if(!property("nopostcaptcha").toBool())
			request->addPostField("captcha", captcha);
		request->addPostField("password", post.password);

		connector()->connectRequest(this, SLOT(resultPost(RequestPtr, const QByteArray&)), 0, request);
		connector()->queue(request);
	}

	void KarehaAgent::createThread(const PostDescriptor& post, const QString& captcha, const BoardConstraints& /*constraints*/)
	{
		m_threadID = 0;
		m_board = post.board;
		QString karehascript = property("karehascript").toString();
		karehascript.replace("%BOARD%", m_board);

		HttpRequestPtr request = connector()->makeHttpRequest(m_host, karehascript, "POST");
//		if(!m_captchaCookie.isEmpty())
//			request->setCookieString("captchakey=" + m_captchaCookie);
		request->addPostField("task", "post");
		request->addPostField("name", "");
		request->addPostField("link", "");
		request->addPostField("title", post.topic);
		request->addPostField(property("field1name").toString(), post.name);
		request->addPostField(property("field2name").toString(), post.email);
		request->addPostField("markup", "waka");
		request->addPostField(property("field4name").toString(), post.text);
		addAttachments(request, post.attachments.count() > 0 ? post.attachments.at(0) : AttachmentDescriptor(), "file");
		if(!property("nothreadcaptcha").toBool())
			request->addPostField("captcha", captcha);
		request->addPostField("password", post.password);

		connector()->connectRequest(this, SLOT(resultPost(RequestPtr, const QByteArray&)), 0, request);
		connector()->queue(request);
	}

	void KarehaAgent::deleteThread(const ThreadId& /*threadId*/, const QString& /* password */)
	{
		// Not implemented yet
	}

	void KarehaAgent::deletePost(const PostId& /*postId*/, const QString& /* password */)
	{
	}

	void KarehaAgent::resultPost(RequestPtr /* r */, const QByteArray& data)
	{
		QString regexp = QString::fromUtf8("<body class=\"errorpage\">.*<h1>([^<>]*)");
		QRegExp rx(regexp);
		if(rx.indexIn(QString::fromUtf8(data)) != -1)
		{
			log(llDebug, "Error: %s", qPrintable(rx.cap(1)));
			emit postingError(rx.cap(1));
			return;
		}
		else
		{
			//emit postingError("");
			// TODO we can emit here 'thread' slot as well
		}
		log(llDebug, "board: %s, thread: %d", qPrintable(m_board), m_threadID);
		emit postingDone(ThreadId(m_host, m_board, m_threadID));
		//emit refresh(m_board, m_threadID, true);
	}

	void KarehaAgent::resultCaptcha(RequestPtr r, const QByteArray& data)
	{
		//m_captchaCookie = r->cookie("captchakey");
		//log(llDebug, "Captcha cookie: %s", qPrintable(m_captchaCookie));
		ThreadId threadId = r->property("thread_id").value<ThreadId>();
		emit captcha(threadId, data);
	}

	void KarehaAgent::resultDelete(RequestPtr /* r */, const QByteArray& /* data */)
	{
		// Vsem pohui
	}

	QStringList KarehaAgent::ratings()
	{
		return QStringList();
	}

	ChanAgent* KarehaAgent::clone(const QString& host)
	{
		return new KarehaAgent(host);
	}

	QString KarehaAgent::id()
	{
		return "kareha";
	}
}

Q_EXPORT_PLUGIN2(karehaagent, Wishmaster::KarehaAgent)

